package com.tbit.uqbike.client.business.user_op_log.service;

import cn.hutool.core.util.ObjUtil;
import com.tbit.common.entity.UserOpLog;
import com.tbit.common.utils.TraceUtil;
import com.tbit.uqbike.client.dao.log.UserOpLogDao;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author <a href="mailto:zheng.zebiao@tbit.com.cn">zb</a>
 * @since 2024/11/26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserOpLogService {
    final UserOpLogDao userOpLogDao;

    public void insertSingle(UserOpLog userOpLog) {
        try {
            StringBuilder detail = new StringBuilder(ObjUtil.defaultIfNull(userOpLog.getDetail(), ""));
            String traceId = TraceUtil.getTraceIdByLocal();
            if (traceId != null) {
                if (detail.length() > 0) {
                    detail.append("\n");
                }
                detail.append("TraceID: ")
                        .append(traceId);
            }
            userOpLog.setDetail(detail.length() > 0 ? detail.toString() : null);
            save(userOpLog);
        } catch (Exception e) {
            log.error("[人员操作日志] 插入失败: {}", userOpLog, e);
        }
    }

    public void save(UserOpLog userOpLog) {
        if (userOpLog.getOpUserPhone() != null && userOpLog.getOpUser() == null) {
            userOpLog.setOpUser("未实名");
        }
        if (userOpLog.getTargetUserPhone() != null && userOpLog.getTargetUser() == null) {
            userOpLog.setTargetUser("未实名");
        }
        userOpLogDao.insert(userOpLog);
    }
}
